#!/usr/bin/env python
# -*- coding: utf-8 -*-

import base64
import timeit
import functools

timefunc = timeit.default_timer


def api_view(http_method_names):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(request, *args, **kwargs):
            if 'GET' in http_method_names:
                http_method_names.append('HEAD')
            if request.command.upper() not in http_method_names:
                result = {'headers': {}, 'content': ''}
                result['headers']['Allow'] = ', '.join(http_method_names)
                result['code'] = 405
            else:
                now = timefunc()
                result = func(request, *args, **kwargs)
                duration = (timefunc() - now) * 1000
                code = result.setdefault('code', 200)
                if code == 200:
                    result['headers']['X-Runtime'] = '%dms' % int(duration)
            return result
        return wrapper
    return decorator


def http_auth_basic(username, password, realm='Login'):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(request, *args, **kwargs):
            authorization = request.headers.getheader('authorization')
            if authorization:
                authorization = authorization.split()
                if len(authorization) == 2:
                    if authorization[0].lower() == 'basic':
                        if authorization[1] == base64.b64encode('%s:%s' % (username, password)):
                            return func(request, *args, **kwargs)
            result = {'headers': {}, 'content': ''}
            result['headers']['WWW-Authenticate'] = 'Basic realm="%s"' % realm
            result['code'] = 401
            return result
        return wrapper
    return decorator
